/**
 * 
 */
package denaris.core.entity;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.Sprite;

import denaris.core.AbstractDenarisMap;
import denaris.core.controller.AbstractController;
import denaris.core.controller.StaticExplosionController;
import denaris.midlet.GameScreen;

/**
 * @author stkl23
 * 
 */
public class Explosion extends AbstractEntity {
	private int childCount = 0;

	private int xPos;

	private int yPos;

	private int frameDelay = 0;

	private int frameCount;

	private boolean turnToCollectible;

	/**
	 * Indicates the satellite type that this explosion should turn into. The
	 * default value of -1 means that it doesn't become a satellite. The types
	 * are listed in the SatelliteTypes interface.
	 */
	private int turnToSatellite = -1;

	public Explosion(AbstractDenarisMap map, int x, int y, int children,
			int delay, boolean toCollectible) {
		super(map, 0);
		xPos = x;
		yPos = y;
		Sprite sprite = controller.getSprite();
		sprite.setPosition(xPos, yPos);
		childCount = children;
		frameDelay = delay;
		frameCount = delay;
		this.turnToCollectible = toCollectible;
	}

	public AbstractController createController() {
		return new StaticExplosionController(0, 0);
	}

	public void update() {
		super.update();
		if (childCount > 0) {
			if (frameCount == 0) {
				childCount--;
				frameCount = frameDelay;
				parentMap.addFriend(new Explosion(getParentMap(), xPos
						+ GameScreen.RANDOM.nextInt() % 20, yPos
						+ GameScreen.RANDOM.nextInt() % 14, 0, 0, turnToCollectible));
			} else {
				frameCount--;
			}
		}
	}

	public void paint(Graphics g) {
		super.paint(g);
	}

	public void onScopeLeft() {
		controller.deactivate();
		Sprite s = controller.getSprite();
		if (turnToCollectible) {
			toCollectible(s.getX(), s.getY());
		} else if (turnToSatellite > -1) {
			toSatellite(s.getX(), s.getY());
		}
		getParentMap().removeFriend(this);
	}

	private void toSatellite(int x, int y) {
		AbstractDenarisMap map = getParentMap();
		Satellite s = new Satellite(map, x, y, turnToSatellite);
		map.addFriend(s);
	}

	private void toCollectible(int x, int y) {
		// create the collectible
		int type = GameScreen.nextPositiveInt(5);

		AbstractDenarisMap map = getParentMap();
		Collectible c = new Collectible(map, x, y, type);
		// add it to the friends list
		map.addFriend(c);
	}

	public boolean shouldCreateCollectible() {
		return GameScreen.RANDOM.nextInt() % 12 == 0;
	}

	public void setTurnToCollectible(boolean turnToCollectible) {
		this.turnToCollectible = turnToCollectible;
	}

	public int getTurnToSatellite() {
		return turnToSatellite;
	}

	public void setTurnToSatellite(int turnToSatellite) {
		this.turnToSatellite = turnToSatellite;
	}
}